package com.red.interceptor;

import com.alibaba.fastjson.JSON;
import com.red.pojo.Result;
import com.red.pojo.model.LoginUser;
import com.red.util.JWTUtil;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class TokenInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        response.setContentType("application/json;charset=UTF-8");

        // 不管有没有登录，都可以进入
        String requestURI = request.getRequestURI();
        if (requestURI.contains("login") ||
                requestURI.contains("register") ||
                requestURI.contains("upload") ||
                requestURI.contains("public")
        ) {
            return true;
        }

        String token = request.getHeader("token");

        // token 携带判断
        if (token == null) {
            response.getWriter().print(JSON.toJSONString(Result.error("需要携带token")));
            return false;
        }

        // token 验证
        if (!JWTUtil.verifyJWT(token)) {
            response.getWriter().print(JSON.toJSONString(Result.error("token验证失败")));
            return false;
        }

        LoginUser loginUser = JWTUtil.getPayload(token, LoginUser.class);

        if (loginUser == null) {
            response.getWriter().print(JSON.toJSONString(Result.error("payload异常")));
            return false;
        }

        long loginTime = System.currentTimeMillis() - loginUser.getLoginTime();
        // 登录许可期限 1 天
        long limit = 1000 * 60 * 60 * 24;

//        token 过期判断
        if (loginTime > limit) {
            response.getWriter().print(JSON.toJSONString(Result.error("token已过期")));
            return false;
        }

        return true;
    }
}
